<template>
  <view class="container">
    <view class="guide">
      <image src="../../static/faceDetect.jpg" mode=""></image>
    </view>
    <view class="picture">
      <image class="image" :src="avatarUrl || '../../static/add.png'" @click="selectImage" />
      <!-- 删除按钮 -->
      <!--  <view v-if="avatarUrl" class="delete-button" @click="removeImage">
        <image src="../../static/square_error.png" />
      </view> -->
    </view>

    <view class="content">
      <view class="content-left">
        <view class="secret">
          开门密码：
        </view>
        <view class="id">
          学工号：
        </view>
      </view>
      <view class="content-right">
        <view class="secret">
          <input disabled="true" v-model="number" />
          <input class="input" v-model="password" maxlength="4" />
        </view>
        <view class="id">
          {{account}}
        </view>
      </view>
    </view>
    <view class="checkbox">
      <checkbox-group v-model="agree" @change="handleCheckboxChange">
        <label>
          <span style="color: red; font-size: 20px;">*</span>
          <checkbox value="agree" />同意采集照片(仅用于门禁)
        </label>
      </checkbox-group>

    </view>
    <view class="btn">
      <button type="primary" @click="uploadImage">提交</button>
    </view>
  </view>
</template>

<script>
  import {
    ajax
  } from "../../utils/request.js";
  export default {
    data() {
      return {
        avatarUrl: '', // 用于存储用户选择的图片路径
        password: '',
        number: '1234',
        account: '',
        agree: false, // 用于控制是否同意采集照片
      };
    },
    onLoad() {
      this.getuserInfo();
    },
    methods: {
      selectImage() {
        uni.chooseImage({
          count: 1, // 默认选择一张
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
          success: (res) => {
            if (res.tempFilePaths.length > 0) {
              const file = res.tempFiles[0];
              const size = file.size / 1024 / 1024; // 将文件大小转换为MB
              if (size > 2) {
                uni.showToast({
                  title: '图片大小不能超过2MB',
                  icon: 'none',
                  duration: 2000
                });
                return;
              }
              this.avatarUrl = res.tempFilePaths[0]; // 更新图片路径

            }
          },
          fail: (err) => {
            console.error('选择图片失败', err);
            uni.showToast({
              title: '选择图片失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      },
      uploadImage() {
        if (!this.agree) {
          uni.showToast({
            title: '请同意采集照片',
            icon: 'none'
          });
          return;
        } else if (!this.avatarUrl) {
          uni.showToast({
            title: '请先上传图片',
            icon: 'none'
          });
          return;
        }
        const formData = {
          XGId: this.account,
          doorpassword: this.number + this.password
        };
        uni.showLoading({
          title: '正在上传...'
        });
        console.log(formData);
        console.log(this.avatarUrl);
        // 上传图片到服务器
        const token = uni.getStorageSync('token');
        let authToken = token.startsWith('Bearer ') ? token.slice(7) : token;
        const uploadTask = uni.uploadFile({
          url: 'https://api.flowergk.com/api/user/uploaduserimage', // 替换为你的上传接口URL
          filePath: this.avatarUrl,
          header: {
            'Authorization': `Bearer ${authToken}`
          } || {},
          name: 'image', // 后端通过这个字段接收文件
          formData: formData, // 非文件参数
          success: (uploadRes) => {
            uni.hideLoading();
            console.log('上传成功', uploadRes);
            if (uploadRes.statusCode === 200) {
              // 上传成功后的操作，例如更新图片路径
              this.avatarUrl = 'static/add-active.png';
            }
          },
          fail: (uploadErr) => {
            console.error('上传失败', uploadErr);
            uni.hideLoading();
            uni.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      },
      removeImage() {
        this.avatarUrl = ''; // 清空 avatarUrl
        uni.removeStorageSync('userInfo'); // 如果有存储用户信息，也一并清除
        uni.showToast({
          title: '图片已删除',
          icon: 'none',
          duration: 2000
        });
      },
      getuserInfo() {
        const userInfo = uni.getStorageSync('userInfo')
        this.account = userInfo.account
      },
      handleCheckboxChange(event) {
        this.agree = event.detail.value.length > 0;
      }
    }
  }
</script>

<style>
  .container {
    display: flex;
    flex-direction: column;
    width: 100vw;
    position: fixed;
  }

  .picture {
    display: flex;
    justify-content: center;
    width: 70%;
    margin: 5% auto;
    /* margin-bottom: 10%; */
  }

  .image {
    width: 125px;
    height: 125px;
  }

  .content {
    width: 70%;
    font-size: 16px;
    display: flex;
    flex-direction: row;
    justify-content: start;
    margin: 0 auto;
  }

  .content-left {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: left;
    height: 80px;
  }

  .content-right {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: start;
    height: 80px;
  }

  .secret {
    display: flex;
    justify-content: center;
    height: 20px;
    line-height: 20px;
  }

  input {
    width: 40px;
    height: 20px;
    line-height: 20px;
  }

  .input {
    width: 60px;
    border-bottom: 0.1px solid #000;
  }

  .guide image {
    width: 100vw;
    height: 40vh;
  }

  .btn {
    width: 70%;
    display: flex;
    justify-content: center;
    margin: 0 auto;
  }

  .btn button {
    width: 400px;
  }

  .delete-button image {
    position: absolute;
    top: -12.5px;
    /* 根据实际情况调整 */
    left: 112.5px;
    /* 根据实际情况调整 */
    width: 25px;
    /* 根据实际情况调整 */
    height: 25px;
    /* 根据实际情况调整 */
  }

  .checkbox {
    display: flex;
    width: 70%;

    margin: 1% auto;
  }
</style>